// $(function () {
//
//
//     $('.my-list-content>a').click(function (ev) {
//         ev.preventDefault(); //阻止默认事件 href
//         // ev.stopPropagation(); // 阻止事件冒泡
//         // return false; // 阻止了冒泡和默认
//
//     });
//
//     //鼠标点击 ul li 下的 active 样式切换
//     $('.my-navbar-nav li').click(function () {
//         $(this).addClass('active').siblings('li').removeClass('active');
//     });
//
//     //模态窗中的标签样式切换
//     $('.pull-left .my-modal-body ul li').click(function () {
//         $(this).addClass('active').siblings('li').removeClass('active');
//         $($('.my-modal-body ul').siblings('div')[$(this).index()]).show().siblings('div').hide();
//
//     });
//
//     //鼠标移入到内容中，显示分享的小图标
//     $('.my-list-content a').each(function (index,ele) {
//         $(this).hover(function () {
//             $($('.pull-left p.my-p-right')[index]).css('display','block');
//         },function () {
//             $($('.pull-left p.my-p-right')[index]).css('display','none');
//         })
//     });
//
//     //鼠标移入到内容的图片上，将小图片变成大图片
//     $('.pull-right img').each(function (index,ele) {
//         $(this).click(function () {
//             if($(this).hasClass('big')){
//                 $(this).animate({width:'64px',height:'64px'},500);
//                 $(this).removeClass('big');
//
//             }else {
//                 $(this).animate({width:'120px',height:'120px'},500);
//                 $(this).addClass('big');
//             }
//         })
//     });
//
//     //注册 选择中国/海外时，区域下拉框的变化
//     $('.my-country').change(function () {
//         if($('.my-country option:selected').val() === '1'){
//             $('.my-info-register .form-inline').hide();
//         }else{
//             $('.my-info-register .form-inline').show();
//         }
//     });
//
//     //推荐的点击事件
//     $('.span_click1').each(function (index,ele) {
//         var isFlag1 = true;
//         $(this).click(function () {
//             var count1 = $($('.span_count1')[index]).text();
//             if(isFlag1){
//                 $($('.span_count1')[index]).text(Number(count1)+1);
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -20px','color':'#58cb05'});
//                 $(this).attr('title','取消推荐');
//                 isFlag1 = false;
//             }else{
//                 $($('.span_count1')[index]).text(Number(count1)-1);
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -40px','color':'#9d9d9d'});
//                 $(this).attr('title','推荐');
//                 isFlag1 = true;
//             }
//         });
//     });
//
//     //评论的点击事件
//     $('.span_click2').each(function (index,ele) {
//         console.log("comment", index);
//         var isFlag2 = true;
//         $(this).click(function () {
//             console.log($(this).index());
//             if(isFlag2){
//                 $($('.my-comment')[index]).show();
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -79px','color':'#63c8ff'});
//                 isFlag2 = false;
//             }else{
//                 $($('.my-comment')[index]).hide();
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -99px','color':'#9d9d9d'});
//                 isFlag2 = true;
//             }
//         })
//     });
//
//     //关闭评论框
//     $('.my-comment .close').each(function (index,ele) {
//         $(this).click(function () {
//             $($('.my-comment')[index]).hide();
//             $($('.span_click2')[index]).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -99px','color':'#9d9d9d'});
//         })
//     });
//
//     //私藏的 点击事件
//     $('.span_click3').each(function (index,ele) {
//         var isFlag3 = true;
//         $(this).click(function () {
//             if(isFlag3){
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -139px','color':'orange'});
//                 $(this).attr('title','移除私藏');
//                 isFlag3 = false;
//             }else{
//                 $(this).css({'background':'url(/static/images/icon_18_118.png) no-repeat 8px -159px','color':'#9d9d9d'});
//                 $(this).attr('title','加入私藏');
//                 isFlag3 = true;
//             }
//         });
//     });
//
//     //评论内容追加到 ul li 中
//     $('.my-comment button').each(function (index,ele) {
//         $(this).bind('click',function () {
//             var date = new Date();
//             var strDate = date.getFullYear() + '-' + Number(date.getMonth())+1 + '-' + date.getDate()
//                 + '&nbsp;&nbsp;' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
//             var comCount = $($('.com-count')[index]).text();
//             var comment = $($('.my-comment textarea')[index]).val();
//
//             var str = "<li class=\"list-group-item\"> <small>" +
//                 "<span class=\"com-span1\"></span>" +
//                 "<span class=\"com-span2\">alice</span> " +
//                 "<span class=\"com-span3\">"+comment+"</span> " +
//                 "<span class=\"com-span4\">"+strDate+"&nbsp;发布</span> " +
//                 "</small></li> ";
//
//             $($('.my-comment ul.list-group')[index]).append(str);
//             $($('.com-count')[index]).text(Number(comCount)+1);
//             $($('.span_count2')[index]).text(Number(comCount)+1);
//             $($('.my-comment textarea')[index]).val('');
//         })
//     });
//
//     //监听页面滚动
//     $(document).scroll(function () {
//         $(document).scrollTop() > 0 ? $('.move-top').show() : $('.move-top').hide();
//     });
//
//     //回到顶部 点击事件
//     $('.move-top').click(function () {
//         $(document.documentElement).animate({scrollTop:'0'},500)
//     });
//
//     //发布页面的导航,内容切换
//     $('.my-publish ul.nav li').click(function () {
//         $(this).addClass('active').siblings('li').removeClass('active');
//         $($('.my-publish ul.nav').siblings('div')[$(this).index()]).show().siblings('div').hide();
//     });
//     // 发布到的切换
//     $('.my-form-a a').click(function () {
//         $(this).addClass('active').siblings('a').removeClass('active');
//     })
//
// });
$(document).ready(function () {
    initpage(0);
    getpage(1);

});

function getpage(pageindex) { //更新页脚
    $.ajax({
        type: "GET",
        url: "/page/",
        success: function (data) {
            data = JSON.parse(data);
            let pages = Math.ceil(data / 5);
            $($('.pagination')).empty();
            let first = "                        <li class=\"page-select\">\n" +
                "                            <a href=\"javascript:topage(1);\" aria-label=\"Previous\">\n" +
                "                                <span aria-hidden=\"true\">&laquo;</span>\n" +
                "                            </a>\n" +
                "                        </li>";
            $($('.pagination')).append(first);
            for (let i = 1; i <= pages; i++) {
                var str = "<li class='page-index'><a href=\"javascript:topage(" + i + ");\"> " + i + " </a></li>";
                if (i === pageindex) {
                    str = "<li class='page-index active'><a href=\"javascript:topage(" + i + ");\"> " + i + " </a></li>";
                }
                $($('.pagination')).append(str);
            }
            let next = "                        <li>\n" +
                "                            <a href=\"javascript:topage(" + pages + ");\" aria-label=\"Next\">\n" +
                "                                <span aria-hidden=\"true\">&raquo;</span>\n" +
                "                            </a>\n" +
                "                        </li>";
            $($('.pagination')).append(next);
        },
        error: function (message) {
            console.log(message);
        }
    })
}

function topage(i) {  //分页刷新
    initpage(i - 1);
    getpage(i)
}

function initpage(page) {
    $.ajax({
        type: "GET",
        url: "/init/?page=" + page,
        success: function (data) {
            let ats = JSON.parse(data);
            data = JSON.parse(data);
            $($('.my-list-article')).empty();
            for (let i = 0; i < ats.length; i++) {
                var content = data[i][3].replace(/\n/g, '<br/>');
                var str = "<div class=\"list-group my-list-content\">" +
                    "<a href=\"#\" class=\"list-group-item clearfix\">" +
                    "<div class=\"pull-left clearfix\" style=\"margin-right: -100px\"><h5>" +
                    data[i][2] + "&nbsp;&nbsp;</h5><br>" + "<small>" + content + "</small> <br>" +
                    "<p class=\"clearfix my-p-left pull-left\">\n" +
                    "                                <span class=\"article_id\" style=\"display: none\">" + data[i][0] + "</span>" +
                    "                                <span class=\"span1 span_click1\" title=\"推荐\"><span class=\"span_count1\">" + data[i][4] + "</span></span>\n" +
                    "                                <span class=\"span2 span_click2\" title=\"评论\"><span class=\"span_count2\" >" + data[i][5] + "</span></span>\n" +
                    "                                <span class=\"span4\"><img style='width: 20px; height: 20px; position: relative; bottom: 4px' src=\"/static/upload/" + data[i][7] + "\" ></span>\n" +
                    "                                <span class=\"span6\">" + data[i][1] + "</span>\n" +
                    "                                <span class=\"span5\">" + data[i][6] + "</span>\n" +
                    "                            </p>" +
                    "                            <p class=\"clearfix my-p-right pull-right\" style=\"margin-right: -150px\">\n" +
                    "                                <span class=\"span1_1\">分享到</span>\n" +
                    "                                <span class=\"span2_1\"></span>\n" +
                    "                                <span class=\"span3_1\"></span>\n" +
                    "                                <span class=\"span4_1\"></span>\n" +
                    "                                <span class=\"span5_1\"></span>\n" +
                    "                            </p>\n" +
                    "                        </div>" +
                    "                    </a>\n" +
                    "                    <div class=\"panel panel-default my-comment\">\n" +
                    "                        <div class=\"panel-heading\">网友评论(<span class=\"com-count\">" + data[i][5] + "</span>)<span class=\"close\">X</span></div>\n" +
                    "                        <div class=\"panel-body\">\n" +
                    "                            <ul class=\"list-group\">\n" +
                    "                            </ul>\n" +
                    "                            <div class=\"form-inline\">\n" +
                    "                                <textarea class=\"form-control\" rows=\"2\"></textarea>\n" +
                    "                                <button type=\"button\" class=\"btn btn-info\">评论</button>\n" +
                    "                            </div>\n" +
                    "                        </div>\n" +
                    "                    </div>"
                ;
                $($('.my-list-article')).append(str);
            }
            init()
        },
        error: function (message) {
            console.log(message);
        }
    })
}

function init() {
    let user = $('.user-name').text();
    if (user === "no") {
        var str = "<li><a style=\"color: black;\" href=\"javascript:registwindow();\">注册</a></li>\n" +
            "                    <li><a style=\"color: black;\" href=\"javascript:loginwindow();\">登录</a></li>";
        $('.user-info').append(str);
    } else {
        $('.user-name').css({
            'display': 'inherit',
            'color': 'black'
        });
    }


    $('.my-list-content>a').click(function (ev) {
        ev.preventDefault(); //阻止默认事件 href
        // ev.stopPropagation(); // 阻止事件冒泡
        // return false; // 阻止了冒泡和默认
    });

    //鼠标点击 ul li 下的 active 样式切换
    $('.my-navbar-nav li').click(function () {
        $(this).addClass('active').siblings('li').removeClass('active');
    });

    //模态窗中的标签样式切换
    $('.pull-left .my-modal-body ul li').click(function () {
        $(this).addClass('active').siblings('li').removeClass('active');
        $($('.my-modal-body ul').siblings('div')[$(this).index()]).show().siblings('div').hide();

    });

    //鼠标移入到内容中，显示分享的小图标
    $('.my-list-content a').each(function (index, ele) {
        $(this).hover(function () {
            $($('.pull-left p.my-p-right')[index]).css('display', 'block');
        }, function () {
            $($('.pull-left p.my-p-right')[index]).css('display', 'none');
        })
    });

    //鼠标移入到内容的图片上，将小图片变成大图片
    $('.pull-right img').each(function (index, ele) {
        $(this).click(function () {
            if ($(this).hasClass('big')) {
                $(this).animate({width: '64px', height: '64px'}, 500);
                $(this).removeClass('big');

            } else {
                $(this).animate({width: '120px', height: '120px'}, 500);
                $(this).addClass('big');
            }
        })
    });

    //注册 选择中国/海外时，区域下拉框的变化
    $('.my-country').change(function () {
        if ($('.my-country option:selected').val() === '1') {
            $('.my-info-register .form-inline').hide();
        } else {
            $('.my-info-register .form-inline').show();
        }
    });

    //推荐的点击事件
    $('.span_click1').each(function (index, ele) {
        var isFlag1 = true;

        $(this).click(function () {
            var count1 = $($('.span_count1')[index]).text();
            var id = $($('.article_id')[index]).text();
            if (isFlag1) {
                addgood(id, Number(count1) + 1);
                $($('.span_count1')[index]).text(Number(count1) + 1);
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -20px',
                    'color': '#58cb05'
                });
                $(this).attr('title', '取消推荐');
                isFlag1 = false;
            } else {
                addgood(id, Number(count1) - 1);
                $($('.span_count1')[index]).text(Number(count1) - 1);
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -40px',
                    'color': '#9d9d9d'
                });
                $(this).attr('title', '推荐');
                isFlag1 = true;
            }
        });
    });

    //评论的点击事件
    $('.span_click2').each(function (index, ele) {
        var isFlag2 = true;
        var id = $($('.article_id')[index]).text();
        $(this).click(function () {
            if (isFlag2) {
                $($('.my-comment')[index]).show();
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -79px',
                    'color': '#63c8ff'
                });
                isFlag2 = false;
                getcomment(id, index);

            } else {
                $($('.my-comment')[index]).hide();
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -99px',
                    'color': '#9d9d9d'
                });
                isFlag2 = true;
            }
        })
    });

    //关闭评论框
    $('.my-comment .close').each(function (index, ele) {
        $(this).click(function () {
            $($('.my-comment')[index]).hide();
            $($('.span_click2')[index]).css({
                'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -99px',
                'color': '#9d9d9d'
            });
        })
    });

    //私藏的 点击事件
    $('.span_click3').each(function (index, ele) {
        var isFlag3 = true;
        $(this).click(function () {
            if (isFlag3) {
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -139px',
                    'color': 'orange'
                });
                $(this).attr('title', '移除私藏');
                isFlag3 = false;
            } else {
                $(this).css({
                    'background': 'url(/static/images/icon_18_118.png) no-repeat 8px -159px',
                    'color': '#9d9d9d'
                });
                $(this).attr('title', '加入私藏');
                isFlag3 = true;
            }
        });
    });

    //评论内容追加到 ul li 中
    $('.my-comment button').each(function (index, ele) {
        $(this).bind('click', function () {
            let user = $('.user-name').text();
            var comment = $($('.my-comment textarea')[index]).val();
            if (user === "no") {
                $('#myModal3').off('hidden.bs.modal');
                $('#myModal3').on('hidden.bs.modal', function () {
                    loginwindow();
                });
                loginError("请先登录!");
            } else {
                console.log("yes", user);
                var id = $($('.article_id')[index]).text();
                $.ajax({
                    type: "POST",
                    url: "/comment/",
                    data: {
                        artid: id,
                        username: user,
                        comment: comment
                    },
                    success: function (data) {
                        console.log("comment error", data);
                    },
                    error: function (message) {
                        console.log(message);
                    }
                });
                let path = $('.user-icon').attr("src");
                var date = new Date();
                var strDate = date.getFullYear() + '-' + Number(date.getMonth() + 1) + '-' + date.getDate()
                    + '&nbsp;&nbsp;' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
                var comCount = $($('.com-count')[index]).text();
                var str = "<li class=\"list-group-item\"> <small>" +
                    "<span class=\"com-span1\"><img style='width: 20px; height: 20px; position: relative; bottom: 4px' src=\"" + path + "\" ></span>" +
                    "<span class=\"com-span2\">" + user + "</span> " +
                    "<span class=\"com-span3\">" + comment + "</span> " +
                    "<span class=\"com-span4\">" + strDate + "&nbsp;发布</span> " +
                    "</small></li> ";

                $($('.my-comment ul.list-group')[index]).append(str);
                $($('.com-count')[index]).text(Number(comCount) + 1);
                $($('.span_count2')[index]).text(Number(comCount) + 1);
                $($('.my-comment textarea')[index]).val('');
            }
        })
    });

    $('.page-index').each(function (index, ele) {
        console.log("PAGE", index);
    });

    //监听页面滚动
    $(document).scroll(function () {
        $(document).scrollTop() > 0 ? $('.move-top').show() : $('.move-top').hide();
    });

    //回到顶部 点击事件
    $('.move-top').click(function () {
        $(document.documentElement).animate({scrollTop: '0'}, 500)
    });

    //发布页面的导航,内容切换
    // $('.my-publish ul.nav li').click(function () {
    //     $(this).addClass('active').siblings('li').removeClass('active');
    //     $($('.my-publish ul.nav').siblings('div')[$(this).index()]).show().siblings('div').hide();
    // });
    // // 发布到的切换
    // $('.my-form-a a').click(function () {
    //     $(this).addClass('active').siblings('a').removeClass('active');
    // })

}


//注册登录页面
function loginwindow() {

    $('#myModal').modal({
        keyboard: false
    });
    /* 为了弹出框 弹出时滚动条不消失 背景不影响*/
    $('body').css('padding-right', '0');
}

function login() {
    let name = $("#usernameInput").val();
    let pswd = $("#passwordInput").val();
    if (name === "" || pswd === "") {
        $('#myModal3').off('hidden.bs.modal');
        $('#myModal3').on('hidden.bs.modal', function () {
            loginwindow();
        });
        loginError("用户名和密码不能为空！");
    } else {
        $.ajax({
            type: "POST",
            url: "/login/",
            data: {
                name: $("#usernameInput").val(),
                password: $("#passwordInput").val()
            },
            success: function (data) {
                if (data === "success") {
                    location.reload();
                } else if (data === "no user") {
                    $('#myModal3').off('hidden.bs.modal');
                    $('#myModal3').on('hidden.bs.modal', function () {
                        loginwindow();
                    });
                    loginError("用户不存在！");
                } else if (data === "pswd wrong") {
                    $('#myModal3').off('hidden.bs.modal');
                    $('#myModal3').on('hidden.bs.modal', function () {
                        loginwindow();
                    });
                    loginError("密码错误！");
                } else {
                    $('#myModal3').off('hidden.bs.modal');
                    loginError(data)
                }
                console.log("login error", data);
            },
            error: function (message) {
                console.log(message);
            }
        });
    }
}

function registwindow() {
    $('#myModal2').modal({
        keyboard: false
    });
    /* 为了弹出框 弹出时滚动条不消失 背景不影响*/
    $('body').css('padding-right', '0');
}

function regist() {
    let name = $("#usernameInput1").val();
    let pswd = $("#passwordInput1").val();
    if (name === "" || pswd === "") {
        $('#myModal3').off('hidden.bs.modal');
        $('#myModal3').on('hidden.bs.modal', function () {
            registwindow();
        });
        loginError("用户名和密码不能为空！");
    } else {
        $.ajax({
            type: "POST",
            url: "/regist/",
            data: {
                name: $("#usernameInput1").val(),
                password: $("#passwordInput1").val()
            },
            success: function (data) {
                if (data === "success") {
                    location.reload();
                } else {
                    if (data === "user exist") {
                        $('#myModal3').off('hidden.bs.modal');
                        $('#myModal3').on('hidden.bs.modal', function () {
                            registwindow();
                        });
                        loginError("用户名已存在！");
                    } else if (data === "zy") {
                        $('#myModal3').off('hidden.bs.modal');
                        $('#myModal3').on('hidden.bs.modal', function () {
                            registwindow();
                        });
                        loginError("这不是你该取的名字！");
                    } else {
                        $('#myModal3').off('hidden.bs.modal');
                        loginError(data);
                    }
                }
                console.log("login error", data);
            },
            error: function (message) {
                console.log(message);
            }
        });
    }
}


//发布
function publishwindow() {
    let user = $('.user-name').text();
    if (user === "no") {
        $('#myModal3').off('hidden.bs.modal');
        $('#myModal3').on('hidden.bs.modal', function () {
            loginwindow();
        });
        loginError("请先登录")
    } else {
        $('#myModal1').modal({
            keyboard: false
        });
        /* 为了弹出框 弹出时滚动条不消失 背景不影响*/
        $('body').css('padding-right', '0');
    }
}

function publish() {
    $.ajax({
        type: "POST",
        url: "/publish/",
        data: {
            name: $('.user-name').text(),
            title: document.getElementById("exampleInputTitle").value,
            text: document.getElementById("exampleInputTextarea1").value
        },
        success: function (data) {
            if (data === "success") {
                location.reload();
            } else {
                console.log("publish error", data);
            }
        },
        error: function (message) {
            console.log(message);
        }
    });
}

function loginError(res) {
    $('#myModal3').modal({
        keyboard: false
    });
    /* 为了弹出框 弹出时滚动条不消失 背景不影响*/
    $('body').css('padding-right', '0');
    $('.login-info').text(res);
}

function ajaxtest() {
    $.ajax({
        type: "GET",
        url: "/ajax/",
        success: function (data) {
            var msg = eval("(" + data + ")");
            console.log("success", msg)
        },
        error: function (message) {
            console.log(message);
        }
    });
}

function addgood(id, good) {
    $.ajax({
        type: "GET",
        url: "/addgood/?id=" + id + "&good=" + good,
        success: function (data) {
            var msg = eval("(" + data + ")");
            console.log("success", msg)
        },
        error: function (message) {
            console.log(message);
        }
    });
}

function getcomment(id, index) {
    $.ajax({
        type: "GET",
        url: "/getcomment/?id=" + id,
        success: function (data) {
            data = JSON.parse(data);
            $($('.my-comment ul.list-group')[index]).empty();
            for (let i = 0; i < data.length; i++) {
                var comCount = $($('.com-count')[index]).text();
                var str = "<li class=\"list-group-item\"> <small>" +
                    "<span class=\"com-span1\"><img style='width: 20px; height: 20px; position: relative; bottom: 4px' src=\"/static/upload/" + data[i][5] + "\" ></span>" +
                    "<span class=\"com-span2\"> " + data[i][3] + "</span> " +
                    "<span class=\"com-span3\">" + data[i][2] + "</span> " +
                    "<span class=\"com-span4\">" + data[i][4] + "&nbsp;发布</span> " +
                    "</small></li> ";
                $($('.my-comment ul.list-group')[index]).append(str);
                $($('.com-count')[index]).text(Number(comCount));
                $($('.span_count2')[index]).text(Number(comCount));
                $($('.my-comment textarea')[index]).val('');
            }
        },
        error: function (message) {
            console.log(message);
        }
    });
}

function clearInput() {
    document.getElementById("exampleInputTextarea1").value = "";
}
